package com.example.opengldemo.earth;

import android.opengl.GLES30;
import android.view.View;

import com.example.opengldemo.util.MatrixState;
import com.example.opengldemo.util.ShaderHandle;
import com.example.opengldemo.util.ShaderUtil;
import com.example.opengldemo.util.ShapeFactory;

import java.nio.FloatBuffer;

public class EarthDemo {

    int mProgram ;

    String vertexShaderPath = "earth/vertex_dq.sh" ;
    String fragShaderPath ="earth/fragment_dq.sh" ;

    int m_U_TextureDayHandle ;
    String m_U_TextureDayHandle_NAME="sTextureDay"  ;
    int m_U_TextureNightHandle ;
    String m_U_TextureNightHandle_NAME="sTextureNight"  ;

    FloatBuffer vertexBuffer ;
    FloatBuffer textureBuffer ;

    int vCount ;

    public EarthDemo(View view){
        initShaderProgram(view);
        initShaderBuffer();
    }

    private void initShaderBuffer() {
        float[] vertexArray = ShapeFactory.getEarthVertexArray(1f , 10);
        vertexBuffer = ShapeFactory.getFloatBuffer(vertexArray) ;
        vCount = vertexArray.length/3 ;
        textureBuffer = ShapeFactory.getFloatBuffer(ShapeFactory.getEarthgenerateTexCoor(10));
    }

    private void initShaderProgram(View view) {
        String vertexRes = ShaderUtil.loadFromAssetsFile(vertexShaderPath , view.getResources()) ;
        String fragRes = ShaderUtil.loadFromAssetsFile(fragShaderPath , view.getResources()) ;
        mProgram = ShaderUtil.createProgram(vertexRes , fragRes) ;
        initHandle(mProgram);

    }
    public ShaderHandle shaderHandle;
    private void initHandle(int program) {
        //vertexShader
        this.shaderHandle = new ShaderHandle(program) ;
        //fragShader
        this.m_U_TextureDayHandle = GLES30.glGetUniformLocation(program , m_U_TextureDayHandle_NAME);
        this.m_U_TextureNightHandle = GLES30.glGetUniformLocation(program , m_U_TextureNightHandle_NAME);
    }

    public void drawSelf(int textureDay , int textureNight){
        shaderHandle.program()
                .bindVertexHandle(vertexBuffer)
                .bindTexCoorsHandle(textureBuffer)
                .bindNormalHandle(textureBuffer)
                .bindCameraHandle()
                .bindMMaxtrixHandle()
                .bindMVPMaxtrixHandle()
                .bindLightHandle()
                .bindDefaultTextureHandle(textureDay);


        GLES30.glActiveTexture(GLES30.GL_TEXTURE3);
        GLES30.glBindTexture(GLES30.GL_TEXTURE_2D , textureNight);

        GLES30.glUniform1i(shaderHandle.get_U_textureHandle(), 0);
        GLES30.glUniform1i(m_U_TextureNightHandle, 3);

        shaderHandle.run(GLES30.GL_TRIANGLES , vCount);



    }
}
